<?php
namespace app\admin\controller;

use think\Db;
use think\facade\Cache;

class Block extends Base
{
	public function block()
	{
        if ($this->request->isPost() && $this->request->isAjax()) {
            $data = Db::table('block')->order('id desc')->select();

            // 返回数据
            $res = [
                'code'  => 0,
                'msg'   => '',
                'count' => count($data),
                'data'  => $data,
            ];

            return json($res);
        }

		return $this->fetch();
	}

    public function blockSave()
    {
        if ($this->request->isPost() && $this->request->isAjax()) {
            $id = $this->request->param('id/d', 0);
            $data = [
                'name'  =>  trim($this->request->param('name/s', '')),
                'content' =>  $this->request->param('editorValue/s', ''),
            ];

            // 校验重复
            $map = [];
            $map[] = ['id', '<>', $id];
            $map[] = ['name', '=', $data['name']];
            if (Db::table('block')->where($map)->count()) {
                $this->result('', 1, '区块名称重复');
            }

            // 添加编辑状态检测
            if ($id) {
                if (!Db::table('block')->where('id', $id)->update($data)) {
                    $this->result('', 1, '编辑区块失败');
                }
            } else {
                if (!Db::table('block')->insert($data)) {
                    $this->result('', 1, '添加区块失败');
                }
            }

            // 更新区块缓存
            Cache::set('block', Db::table('block')->column('content', 'id'));

            $this->result('', 0, '保存成功');
        }
    }

    public function blockDel()
    {
        if ($this->request->isPost() && $this->request->isAjax()) {
            $id = $this->request->param('id/d', 0);

            if (!Db::table('block')->delete($id)) {
                $this->result('', 1, '删除失败');
            }

            // 更新区块缓存
            Cache::set('block', Db::table('block')->column('content', 'id'));

            $this->result('', 0, '删除成功');
        }
    }
}
